from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from user.util.process import parse_all, parse_single
from threading import Thread
import user.util.db_util as db_util


def parse_single_document(request):
    '''
    解析单个文件
    single_path: D:\jobs\data\pubmed24n0001.xml
    :param request:
    :return:
    '''
    if request.method == 'GET':
        xml_obj = request.GET.get('single_path')
        batch_size = request.GET.get('batch_size')
        row_id = request.GET.get('id')
        if batch_size is None:
            batch_size = 2000
        print('xml: {0}'.format(xml_obj))
        if not xml_obj.endswith('.xml'):
            return HttpResponse("文件类型错误！")

        try:
            thread1 = Thread(target=parse_single, args=(xml_obj, batch_size, row_id))
            thread1.start()
            # return HttpResponse("succeed!")
            # dict_data = parse_single(xml_obj, batch_size)
            dict_data = {'nodeCount': 0, 'edgeCount': 0}
            return JsonResponse(dict_data)
        except Exception as e:
            print("{0} parse failure".format(xml_obj), e)
            return HttpResponse("failure！".format(e))

    else:
        return HttpResponse("This url only accepts GET requests.")


def parse_all_document(request):
    '''
    解析所有的xml文件
    path: D:\data
    :param request:
    :return:
    '''
    if request.method == 'GET':
        xml_obj_list = request.GET.get('path')
        batch_size = request.GET.get('batch_size')
        if batch_size is None:
            batch_size = 2000
        print('xml path: {0}'.format(xml_obj_list))
        try:

            parse_all(xml_obj_list, batch_size)
            return HttpResponse("succeed！")
        except Exception as e:
            print("parse failure", e)
            return HttpResponse("failure！".format(e))

    else:
        return HttpResponse("This url only accepts GET requests.")


def clear_table(request):
    if request.method == 'GET':
        db_name = request.GET.get('dbName')
        row_id = request.GET.get('id')
        print("view db name:{0}".format(db_name))
        thread1 = Thread(target=db_util.clear_table_data, args=(db_name, row_id))
        thread1.start()

        # db_util.clear_table_data(db_name)
        return HttpResponse("succeed！")
    else:
        return HttpResponse("This url only accepts GET requests.")
